/**
 * 点赞记录表
 */

const { Sequelize ,Model } = require("sequelize");
const { sequelize } = require('@core/db.js')
const {
  ArtIsLikeException,
  ArtIsDisLikeException,
  ArtNotExistException
} = require('@core/http-exception.js')
const { Art } = require('@model/art.js')

class Favor extends Model {
  static async like (artId, type, uid) {
    // 查询，favor表是否已经存在这条记录
    const favor = await Favor.findOne({
      where: {
        artId,
        type,
        uid
      }
    })
    if (favor) {
      throw new ArtIsLikeException()
    }
    await sequelize.transaction(async transaction => {
      await Favor.create({
        artId,
        type,
        uid
      }, {
        transaction
      })
      const art = await Art.getDetail(artId, type)
      if (!art) {
        throw new ArtNotExistException('查询不到数据')
      }
      await art.increment('fav_nums', {
        by: 1
      }, {
        transaction
      })
    })
  }
  static async dislike (artId, type, uid) {
    // 查询favor是否存在
    const favor = await Favor.findOne({
      where: {
        artId,
        type,
        uid
      }
    })
    if (!favor) {
      throw new ArtIsDisLikeException()
    }
    await sequelize.transaction(async transaction => {
      // 先删除记录
      await Favor.destroy({
        where: {
          artId,
          type,
          uid
        }
      }, {
        transaction
      })
      // 给相应的art数据，点赞数减一
      const art = await Art.getDetail(artId, type)
      if (!art) {
        throw new ArtNotExistException('要取消点赞的作品不存在')
      }
      await art.decrement('fav_nums', {
        by: 1
      }, {
        transaction
      })
    })
  }
}

Favor.init({
  artId: Sequelize.INTEGER,
  type: Sequelize.INTEGER,
  uid: Sequelize.INTEGER
}, {
  sequelize,
  tableName: 'favor'
})

module.exports = {
  Favor
}